import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, Toggle, AlertController, LoadingController, Events} from 'ionic-angular';
import {AlertInputOptions, AlertButton, AlertOptions} from 'ionic-angular/components/alert/alert-options';

import {UnlockService} from '../../../services/native/authentication/authentication.service';
import {ToastService} from '../../../services/common/toast.service';

@IonicPage()
@Component({
    selector: 'page-fingerprint-setting',
    templateUrl: 'fingerprint-setting.html',
})
export class FingerprintSettingPage {

    public isFingerprintEnabled: boolean;
    private disabledNextEvent: boolean;

    constructor(private navCtrl: NavController,
                private navParams: NavParams,
                private events: Events,
                private alertCtrl: AlertController,
                public loadCtr: LoadingController,
                private toastService: ToastService,
                private unlockService: UnlockService) {

        this.disabledNextEvent = false;

        this.unlockService.isFingerprintEnabled().then(enabled => {
            this.isFingerprintEnabled = enabled;
        });
    }

    ionViewDidLoad() {
    }

    onSwitchClick(toggle: Toggle) {
        console.log(toggle.value)
    }

    showAlert(msg, callback?) {
        this.alertCtrl.create({
            message: msg,
            cssClass: 'custom-alert',
            buttons: [{
                role: 'cancel',
                text: '确定',
                handler: data => {
                    callback && callback();
                }
            }]
        }).present();
    }

    onSwitchChange() {
        /*this.isFingerprintEnabled = !this.isFingerprintEnabled;*/
        const inputOptions: AlertInputOptions = {
            name: 'password',
            placeholder: '请输入您的登录密码',
            type: 'password'
        };
        const hiddenOptions: AlertInputOptions = {
            name: 'switch',
            type: 'hidden',
        };
        const cancelButton: AlertButton = {
            text: '取消',
            role: 'cancel',
            handler: data => {
            }
        };
        const okButton: AlertButton = {
            text: '确定',
            handler: data => {
                if (!data.password) {
                    this.showAlert('请输入登录密码');
                    return;
                }
                let loading = this.loadCtr.create({
                    spinner: 'circles',
                    content: "验证中",
                });

                loading.present();
                this.unlockService.validatePassword(data.password).then(result => {
                    loading.dismiss();
                    if (result === 'offLine') {
                        //断网
                        //this.showAlert('网络问题，请重试');
                        this.events.publish('checkNet');
                        return;
                    }
                    if (result === 'fail') {
                        this.unlockService.passwordRemainAttemps().then(remain => {
                            if (remain > 0) {
                                this.showAlert(`验证失败,还可以输入${remain}次`);
                            }
                            else {
                                this.showAlert('验证错误次数已达上限，请重新登录');
                            }
                        });

                        this.disabledNextEvent = true;
                        return;
                    }

                    if (result === 'netWork') {
                        this.showAlert('当前网络环境异常，请稍后重');
                        //this.events.publish('checkNet')
                        return;
                    }

                    let enabled = !this.isFingerprintEnabled;
                    this.isFingerprintEnabled = enabled;
                    this.unlockService.switchFingerprintLogin(enabled);
                }, () => {
                    loading.dismiss();
                })
            }
        };
        const alertOptions: AlertOptions = {
            message: '身份验证',
            cssClass: "assist-login-alert-message",
            inputs: [inputOptions, hiddenOptions],
            buttons: [cancelButton, okButton]
        };

        if (this.isFingerprintEnabled) {
            // 关闭指纹时验证
            hiddenOptions.value = false.toString();
            this.alertCtrl.create(alertOptions).present();
        }
        else {
            this.unlockService.isGraphicEnabled().then(enabled => {
                if (enabled) {
                    this.showAlert('启用指纹解锁将会关闭手势密码', () => {
                        hiddenOptions.value = true.toString();
                        this.alertCtrl.create(alertOptions).present();
                    });
                }
                else {
                    if (navigator.onLine) {
                        //有网情况，表示设置成功
                        this.isFingerprintEnabled = true;
                        this.unlockService.switchFingerprintLogin(true);
                    }else{
                        this.events.publish('checkNet');
                    }
                }
            })

        }
    }
}
